package com.aubrey.threadDemo.create;

/**
 * 案例：子线程循环10次-主线程循环20次-二者交替50次-
 * @author Administrator
 *
 */
public class ThreadCom {
	
	private static Bussiness bussiness;
	
	public static void main(String[] args) {
		ThreadCom tcom = new ThreadCom();
		tcom.init();
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				for (int i = 0; i < 50; i++) {
//					synchronized (ThreadCom.class) {
//						for (int j = 0; j < 10; j++) {
//							System.out.println("======第"+i+"次循环；子线程循环第：" + j +"次；");
//						}
//					}
					bussiness.sub(i);
				}
				
			}
		}).start();
		
		for (int i = 0; i < 50; i++) {
//			synchronized (ThreadCom.class) {
//				for (int j = 0; j < 20; j++) {
//					System.out.println("*******第"+i+"次循环；主线程循环第：" + j +"次；");
//				}
//			}
			bussiness.main(i);
		}
	}
	
	public void init(){
		bussiness = new Bussiness();
	}
	
	class Bussiness{
		
		private boolean subFlag = true;
		
		public synchronized void main(int i ) {
//			if(subFlag) {
			while(subFlag) {
				try {
					this.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			} 	
			for (int j = 0; j < 20; j++) {
				if(j==19)System.out.println("主主主主主第"+i+"次循环；主线程循环第：" + j +"次；");
			}
			subFlag = true;
			this.notifyAll();
			
		}
		
		public synchronized void sub(int i ) {
//			if(!subFlag) {
			while(!subFlag) {
				try {
					wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			for (int j = 0; j < 10; j++) {
				if(j==9)System.out.println("子子子子子第"+i+"次循环；子线程循环第：" + j +"次；");
			}
			
			subFlag = false;
			this.notifyAll();
			
		}
		
	}


}


